package com.scs.application.modules.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.modules.base.dto.ExpandColumnDTO;
import com.scs.application.modules.base.entity.PackTemplet;
import com.scs.application.modules.base.entity.PackTempletItem;
import com.scs.application.modules.base.service.PackTempletItemService;
import com.scs.application.modules.base.service.PackTempletService;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 */
@RestController
@RequestMapping("/base/pack_templet")
public class PackTempletController extends CrudController<PackTempletService, PackTemplet>{

    @Autowired
    private PackTempletItemService packTempletItemService;

    private void fillEntity(PackTemplet entity) {
        entity.setCountDtl(packTempletItemService.count(Wrappers.<PackTempletItem>query().select("id").eq("pack_templet_id",entity.getId())));
    }

    /**
     * 根据ID查找数据
     */
    @GetMapping("/find")
    public RestResult find(@RequestParam("id") Serializable id) {
        PackTemplet entity = service.getById(id);
        if (entity == null) {
            return RestResult.error("数据查询失败<br>可能所操作数据已被删除，请刷新后重新尝试操作");
        }
        fillEntity(entity);
        return RestResult.ok("获取数据成功", entity);
    }


    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody PackTemplet entity) {
        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        fillEntity(entity);
        return RestResult.ok("数据保存成功", entity);
    }
    /**
     * 模板视图选择使用
     */
    @GetMapping("/pageForSelect")
    public PageResult pageForSelect(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> userParam =null;
        //固定参数
        if(reqData.containsKey("userParam")){
            JSONObject ob = JSON.parseObject(reqData.get("userParam")+"");
            userParam= Maps.newHashMap(ob);
        }

        IPage pageResult = service.pageForSelect(queryContext,userParam);
        if (pageResult.getTotal() > 0) {
            List<String> packTempletIdList = Lists.newArrayList();

            for(Object object : pageResult.getRecords()){
                PackTemplet packTemplet = (PackTemplet) object;
                packTempletIdList.add(packTemplet.getId());
            }
            List<PackTempletItem> packTempletItemList = packTempletItemService.list(Wrappers.<PackTempletItem>query().in("pack_templet_id",packTempletIdList));
            if (packTempletItemList != null && packTempletItemList.size() > 0) {
                Map<String,List<PackTempletItem>> itemMap = packTempletItemList.stream().collect(Collectors.groupingBy(PackTempletItem::getPackTempletId));
                List<ExpandColumnDTO> childCols;
                ExpandColumnDTO expandColumnDTO;

                for(Object object : pageResult.getRecords()){
                    PackTemplet packTemplet = (PackTemplet) object;
                    packTemplet.setChildData(itemMap.get(packTemplet.getId()));

                    childCols = new ArrayList<>();
                    expandColumnDTO = new ExpandColumnDTO();
                    expandColumnDTO.setField("matrName").setTitle("商品名称");
                    childCols.add(expandColumnDTO);

                    expandColumnDTO = new ExpandColumnDTO();
                    expandColumnDTO.setField("matrSpec").setTitle("商品规格").setColumnWidth(100);
                    childCols.add(expandColumnDTO);

                    expandColumnDTO = new ExpandColumnDTO();
                    expandColumnDTO.setField("packageUnit").setTitle("包装单位").setColumnWidth(80);
                    childCols.add(expandColumnDTO);

                    expandColumnDTO = new ExpandColumnDTO();
                    expandColumnDTO.setField("packageQty").setTitle("包装数量").setColumnWidth(80);
                    childCols.add(expandColumnDTO);

                    expandColumnDTO = new ExpandColumnDTO();
                    expandColumnDTO.setField("amount").setTitle("金额").setColumnWidth(80);
                    childCols.add(expandColumnDTO);
                    packTemplet.setChildCols(childCols);
                }
            }



        }
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }
}
